package com.nsapi.niceschoolapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nsapi.niceschoolapi.common.base.PageData;
import com.nsapi.niceschoolapi.common.config.MySysUser;
import com.nsapi.niceschoolapi.common.util.Constants;
import com.nsapi.niceschoolapi.common.util.Encodes;
import com.nsapi.niceschoolapi.common.util.ResponseEntity;
import com.nsapi.niceschoolapi.entity.Role;
import com.nsapi.niceschoolapi.entity.User;
import com.nsapi.niceschoolapi.service.RoleService;
import com.nsapi.niceschoolapi.service.UserService;
import jdk.management.resource.internal.inst.UnixAsynchronousServerSocketChannelImplRMHooks;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("admin/system/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 跳入用户列表页
     *
     * @return
     */
    @RequestMapping("list")
    public String toListView() {
        return "admin/user/list";
    }

    /**
     * 按条件查询用户列表
     */
    @RequiresPermissions("sys:user:list")
    @PostMapping("list")
    @ResponseBody
    public PageData<User> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                               ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        PageData<User> userPageData = new PageData<>();
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        if (!map.isEmpty()) {
            String type = (String) map.get("type");
            String keys = (String) map.get("key");
            if (StringUtils.isNotBlank(type)) {
                userWrapper.eq("is_admin", "admin".equals(type) ? true : false);
            }
            if (StringUtils.isNotBlank(keys)) {
                userWrapper.and(wrapper -> wrapper.like("login_name", keys).or().like("tel", keys).or().like("email", keys));
            }
        }
        IPage<User> userPage = userService.page(new Page<>(page, limit), userWrapper);
        userPageData.setCount(userPage.getTotal());
        userPageData.setData(userPage.getRecords());
        return userPageData;
    }

    /**
     * 跳入添加用户页
     */
    @RequestMapping("add")
    public String toAddView(ModelMap modelMap) {
        List<Role> roleList = roleService.selectAll();
        modelMap.put("roleList", roleList);
        return "admin/user/add";
    }

    /**
     * 添加用户
     */
    @RequiresPermissions("sys:user:add")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity add(@RequestBody User user) {
        //设置默认密码
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(Constants.DEFAULT_PASSWORD);
        }
        userService.saveUser(user);
        if (StringUtils.isBlank(user.getId())) {
            return ResponseEntity.failure("保存用户信息出错");
        }
        //保存用户角色关系
        userService.saveUserRoles(user.getId(), user.getRoleLists());
        return ResponseEntity.success("操作成功");
    }

    /**
     * 跳转修改用户页
     * 查询用户信息并传入
     */
    @RequestMapping("edit")
    public String toEditView(String id, Model model) {
        User user = userService.findUserById(id);
        List<Role> roleList = roleService.selectAll();
        String roleIds = "";
        if (user != null) {
            roleIds = user.getRoleLists().stream().map(role -> role.getId()).collect(Collectors.joining(","));
        }
        model.addAttribute("localuser", user);
        model.addAttribute("roleList", roleList);
        model.addAttribute("roleIds", roleIds);
        return "admin/user/edit";
    }

    /**
     * 修改用户信息
     */
    @RequiresPermissions("sys:user:edit")
    @PostMapping("edit")
    @ResponseBody
    public ResponseEntity edit(@RequestBody User user) {
        userService.updateUser(user);
        return ResponseEntity.success("操作成功");
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("sys:user:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseEntity.failure("用户id为空");
        }
        User user = userService.findUserById(id);
        if (user == null) {
            return ResponseEntity.failure("此用户不存在");
        }
        userService.deleteUser(user);
        return ResponseEntity.success("操作成功");
    }

    /**
     * 批量删除
     */
    @RequiresPermissions("sys:user:delete")
    @PostMapping("deleteSome")
    @ResponseBody
    public Object deleteSome(@RequestBody List<User> users) {
        if (users == null || users.size() == 0) {
            return ResponseEntity.failure("请选择需要删除的用户");
        }
        for (User u : users) {
            userService.deleteUser(u);
        }
        return ResponseEntity.success("操作成功");
    }

    /**
     * 锁定
     */
    @RequiresPermissions("sys:user:lock")
    @RequestMapping("lock")
    @ResponseBody
    public Object lock(String id) {
        User user = userService.findUserById(id);
        if (user == null) {
            return ResponseEntity.failure("此用户已不存在");
        }
        userService.lockUser(user);
        return ResponseEntity.success("操作成功");
    }

    /**
     * 个人资料
     */
    @RequestMapping("userInfo")
    public String toUserInfoView(Model model) {
        String id = MySysUser.id();
        User user = userService.findUserById(id);
        model.addAttribute("userinfo", user);
        model.addAttribute("userRole", user.getRoleLists());
        return "admin/user/userInfo";
    }

    //保存个人信息
    @RequestMapping("saveUserinfo")
    @ResponseBody
    public Object saveUserInfo(User user) {
        userService.updateById(user);
        return ResponseEntity.success("操作成功");
    }

    // 跳转修改密码页,并获取当前登录用户对象信息传入
    @RequestMapping("changePassword")
    public String tochangePasswordView(Model model) {
        User currUser = userService.getById(MySysUser.id());
        model.addAttribute("currentUser",currUser);
        return "admin/user/changePassword";
    }

    // 修改密码
    @PostMapping("changePassword")
    @ResponseBody
    public Object changePassword(
            @RequestParam(value = "oldPwd",required = false)String oldPwd,
            @RequestParam(value = "newPwd",required = false)String newPwd,
            @RequestParam(value = "confirmPwd",required = false)String confirmPwd) {
        User user = userService.findUserById(MySysUser.id());
        byte[] hashPassword = Encodes.sha1(oldPwd.getBytes(), Encodes.SHA1, Encodes.decodeHex(user.getSalt()), Constants.HASH_INTERATIONS);
        String password = Encodes.encodeHex(hashPassword);
        if (!password.equals(user.getPassword())) {
            return ResponseEntity.failure("旧密码不正确！");
        }
        user.setPassword(newPwd);
        Encodes.entryptPassword(user);
        userService.updateById(user);
        return ResponseEntity.success("操作成功");
    }

    // 头像上传
    @PostMapping("uploadFace")
    @ResponseBody
    public ResponseEntity uploadFile(@RequestParam("icon") MultipartFile file, HttpServletRequest request) {
        if(file == null){
            return ResponseEntity.failure("上传文件为空 ");
        }
        String url = null;
        Map map = new HashMap();
        try {
            url = userService.upload(file);
            map.put("url", url);
            map.put("name", file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failure(e.getMessage());
        }
        return ResponseEntity.success("操作成功").setAny("data",map);

    }

}
